<template>
  <BaseModal 
    v-model="visible" 
    title="忘记密码"
    size="medium"
    @close="handleClose"
  >
    <!-- Logo区域 -->
    <div class="logo-section">
      <div class="logo-circle">
        <div class="logo-inner">
          <el-icon size="28"><Key /></el-icon>
        </div>
      </div>
      <h3 class="modal-subtitle">通过邮箱验证重置您的密码</h3>
    </div>
    
    <!-- 忘记密码表单 -->
    <el-form :model="forgotPasswordForm" :rules="forgotPasswordRules" ref="forgotPasswordFormRef" class="apple-form">
        <el-form-item prop="username" label="用户名">
          <el-input 
            v-model="forgotPasswordForm.username" 
            placeholder="请输入用户名"
            size="large"
            class="apple-input"
            clearable
          >
            <template #prefix>
              <el-icon class="input-icon"><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="email" label="邮箱地址">
          <el-input 
            v-model="forgotPasswordForm.email" 
            placeholder="请输入邮箱地址"
            size="large"
            class="apple-input"
            clearable
          >
            <template #prefix>
              <el-icon class="input-icon"><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="newPassword" label="新密码">
          <el-input 
            type="password" 
            v-model="forgotPasswordForm.newPassword" 
            placeholder="请输入新密码"
            size="large"
            class="apple-input"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon class="input-icon"><Lock /></el-icon>
            </template>
          </el-input>
          <div class="password-hint">密码长度应在6-18个字符之间</div>
        </el-form-item>
        
        <el-form-item prop="verificationCode" label="验证码">
          <div class="verification-input">
            <el-input 
              v-model="forgotPasswordForm.verificationCode" 
              placeholder="请输入验证码"
              size="large"
              class="apple-input verification-code-input"
              clearable
              maxlength="6"
              oninput="value=value.replace(/[^0-9]/g,'')"
            >
              <template #prefix>
                <el-icon class="input-icon"><Key /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary" 
              size="large"
              :disabled="countdown > 0 || sendingCode"
              @click="sendVerificationCode"
              class="send-code-btn"
            >
              {{ countdown > 0 ? `${countdown}s` : (sendingCode ? '发送中...' : '发送验证码') }}
            </el-button>
          </div>
        </el-form-item>
      
      <div class="form-actions">
        <el-button 
          type="primary" 
          @click="submitForm" 
          size="large" 
          class="apple-button"
          :loading="loading"
          :disabled="isSubmitDisabled"
        >
          <span v-if="!loading">重置密码</span>
          <span v-else>重置中...</span>
        </el-button>
      </div>
    </el-form>
    
    <!-- 底部链接 -->
    <template #footer>
      <div class="auth-links">
        <el-button type="text" @click="goToLogin" class="apple-link">
          返回登录
        </el-button>
        <el-button type="text" @click="goToRegister" class="apple-link">
          还没有账号？立即注册
        </el-button>
      </div>
    </template>
  </BaseModal>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { User, Message, Lock, Key } from '@element-plus/icons-vue';
import { sendForgotPasswordCode, resetPasswordByCode } from '../../api/auth';
import BaseModal from '../Modals/BaseModal.vue';

interface Props {
  modelValue: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  'close': [];
  'switch-to-login': [];
  'switch-to-register': [];
}>();

const router = useRouter();
const forgotPasswordFormRef = ref<FormInstance>();
const loading = ref(false);
const sendingCode = ref(false);
const countdown = ref(0);
let countdownTimer: ReturnType<typeof setInterval> | null = null;

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
});

const forgotPasswordForm = reactive({
  username: '',
  email: '',
  newPassword: '',
  verificationCode: '',
});

const forgotPasswordRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '用户名长度在 3 到 15 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度在 6 到 18 个字符', trigger: 'blur' },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码为6位数字', trigger: 'blur' },
    { pattern: /^[0-9]{6}$/, message: '验证码必须为6位数字', trigger: 'blur' },
  ],
});

// 计算提交按钮是否禁用
const isSubmitDisabled = computed(() => {
  return (
    !forgotPasswordForm.username ||
    !forgotPasswordForm.email ||
    !forgotPasswordForm.newPassword ||
    !forgotPasswordForm.verificationCode ||
    loading.value
  );
});

// 发送验证码
const sendVerificationCode = async () => {
  if (!forgotPasswordForm.username || !forgotPasswordForm.email) {
    ElMessage.warning('请先填写用户名和邮箱');
    return;
  }
  
  sendingCode.value = true;
  try {
    await sendForgotPasswordCode({
      username: forgotPasswordForm.username,
      email: forgotPasswordForm.email,
    });
    
    ElMessage.success('验证码已发送到您的邮箱');
    startCountdown();
  } catch (error: any) {
    console.error('发送验证码失败:', error);
    ElMessage.error(error.response?.data?.message || '发送验证码失败');
  } finally {
    sendingCode.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  countdownTimer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer!);
      countdownTimer = null;
    }
  }, 1000);
};

// 提交表单
const submitForm = () => {
  if (!forgotPasswordFormRef.value) return;
  
  // 添加调试信息
  console.log('表单数据:', forgotPasswordForm);
  
  forgotPasswordFormRef.value.validate(async (valid, fields) => {
    console.log('表单验证结果:', valid);
    console.log('验证失败的字段:', fields);
    
    if (valid) {
      loading.value = true;
      try {
        await resetPasswordByCode({
          email: forgotPasswordForm.email,
          code: forgotPasswordForm.verificationCode,
          newPassword: forgotPasswordForm.newPassword,
        });
        
        ElMessage.success({
          message: '密码重置成功，请使用新密码登录',
          type: 'success',
          duration: 3000
        });
        
        // 延迟关闭模态框
        setTimeout(() => {
          handleClose();
          goToLogin();
        }, 1500);
        
      } catch (error: any) {
        console.error('重置密码失败:', error);
        ElMessage.error(error.response?.data?.message || '重置密码失败');
      } finally {
        loading.value = false;
      }
    } else {
      // 显示具体的验证错误信息
      if (fields) {
        const errorMessages = Object.values(fields).flat().map((error: any) => error.message);
        ElMessage.error(errorMessages.join(', '));
      } else {
        ElMessage.warning('请填写完整且正确的信息');
      }
    }
  });
};

const handleClose = () => {
  emit('update:modelValue', false);
  emit('close');
};

const goToLogin = () => {
  handleClose();
  emit('switch-to-login');
};

const goToRegister = () => {
  handleClose();
  emit('switch-to-register');
};

// 清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style scoped>
/* Logo区域 */
.logo-section {
  text-align: center;
  margin-bottom: 32px;
  animation: fadeInDown 0.5s ease-out;
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.logo-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto 16px;
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
  }
  50% {
    box-shadow: 0 8px 30px rgba(102, 126, 234, 0.5);
  }
  100% {
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
  }
}

.logo-inner {
  width: 52px;
  height: 52px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #667eea;
}

.modal-subtitle {
  font-size: 16px;
  color: #86868b;
  margin: 0;
  font-weight: 400;
  line-height: 1.5;
}

/* 表单样式 */
.apple-form {
  margin-bottom: 16px;
}

/* 调整el-form-item的标签样式 */
:deep(.el-form-item__label) {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  line-height: 1.4;
}

/* 调整el-form-item的默认间距 */
:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item:last-of-type) {
  margin-bottom: 0;
}

/* 苹果风格输入框 */
.apple-input {
  width: 100%;
}

:deep(.apple-input .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  padding: 12px 16px;
  transition: all 0.2s ease;
  min-height: 48px;
  display: flex;
  align-items: center;
}

:deep(.apple-input .el-input__wrapper:hover) {
  border-color: rgba(102, 126, 234, 0.4);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

:deep(.apple-input.is-focus .el-input__wrapper) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.apple-input .el-input__inner) {
  font-size: 16px;
  color: #1d1d1f;
  font-weight: 400;
  height: 24px;
  line-height: 24px;
}

:deep(.apple-input .el-input__inner::placeholder) {
  color: #86868b;
}

.input-icon {
  color: #86868b;
  font-size: 18px;
}

/* 密码提示 */
.password-hint {
  font-size: 12px;
  color: #86868b;
  margin-top: 6px;
  padding-left: 2px;
  line-height: 1.4;
}

/* 验证码输入区域 */
.verification-input {
  display: flex;
  gap: 12px;
  align-items: center;
}

.verification-input .apple-input {
  flex: 1;
}

.verification-code-input {
  flex: 1;
}

/* 针对小屏幕优化验证码区域 */
@media (max-width: 480px) {
  .verification-input {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .send-code-btn {
    min-width: auto;
  }
}

.send-code-btn {
  min-width: 120px;
  white-space: nowrap;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-size: 14px;
  font-weight: 500;
  color: white;
  box-shadow: 0 4px 14px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-code-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.send-code-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
}

.send-code-btn.is-disabled {
  background: #f0f0f0;
  color: #999;
  box-shadow: none;
  transform: none;
}

/* 表单操作区域 */
.form-actions {
  margin-top: 32px;
  text-align: center;
}

/* 苹果风格按钮 */
.apple-button {
  width: 100%;
  height: 48px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-size: 16px;
  font-weight: 600;
  color: white;
  box-shadow: 0 4px 14px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.apple-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

:deep(.apple-button:active) {
  transform: translateY(0);
  box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
}

:deep(.apple-button.is-disabled) {
  background: linear-gradient(135deg, #cccccc 0%, #999999 100%);
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.1);
  cursor: not-allowed;
  transform: none;
}

:deep(.apple-button.is-disabled:hover) {
  transform: none;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.1);
}

/* 底部链接 */
.auth-links {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 16px 0;
}

.apple-link {
  font-size: 14px;
  color: #667eea;
  font-weight: 500;
  padding: 0;
  transition: all 0.2s ease;
}

:deep(.apple-link:hover) {
  color: #5a6fd8;
  transform: translateY(-1px);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .logo-circle {
    width: 50px;
    height: 50px;
  }
  
  .logo-inner {
    width: 42px;
    height: 42px;
  }
  
  .modal-subtitle {
    font-size: 14px;
  }
  
  .verification-input {
    flex-direction: column;
  }
  
  .send-code-btn {
    width: 100%;
    height: 44px;
  }
  
  .auth-links {
    flex-direction: column;
    gap: 12px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }
  
  .form-actions {
    margin-top: 24px;
  }
}

@media (max-width: 480px) {
  .logo-section {
    margin-bottom: 24px;
  }
  
  .modal-subtitle {
    font-size: 13px;
    padding: 0 10px;
  }
  
  :deep(.apple-input .el-input__inner) {
    font-size: 15px;
  }
  
  .password-hint {
    font-size: 11px;
  }
}
</style>